package com.yzy.service.impl;

import com.yzy.domain.entity.system.Account;
import com.yzy.exception.VisionException;
import com.yzy.mapper.system.AccountMapper;
import com.yzy.service.AccountService;
import com.yzy.util.algorithm.BCryptPassword;
import com.yzy.util.algorithm.JWTUtils;
import com.yzy.domain.vo.system.AccountVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountMapper accountMapper;

    @Override
    public String loginByUserName(HttpServletRequest request, String loginByUserName, String password, HttpServletResponse response) throws VisionException {
        Account account = accountMapper.findByUsername(loginByUserName);
        return login(account, password);
    }

    @Override
    public Account findById(String id) {
        return Optional.ofNullable(accountMapper.selectById(id)).orElseThrow(
                () -> new VisionException(HttpStatus.NOT_FOUND, "用户不存在！")
        );
    }

    @Override
    public AccountVo findVoById(String id) {
        return accountMapper.findVoById(id);
    }

    @Override
    public Account getAccountFromRequest(HttpServletRequest request) {
        String id = JWTUtils.getIdFromRequest(request);
        return findById(id);
    }

    private String login(Account account, String password) {
        if (null == account) {
            throw new VisionException(HttpStatus.METHOD_NOT_ALLOWED, "用户不存在, 请检查号码是否正确");
        }

        if (StringUtils.isBlank(password)) {
            throw new VisionException(HttpStatus.METHOD_NOT_ALLOWED, "密码错误，请重试");
        }

        Boolean isChecked = BCryptPassword.decodePassword(password, account.getPassword());
        if (!isChecked) {
            throw new VisionException(HttpStatus.METHOD_NOT_ALLOWED, "密码错误，请重试");
        }
        return JWTUtils.sign(account.getId());
    }
}
